package ru.jexp.rcp.supply.login;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.osgi.service.prefs.BackingStoreException;

import ru.jexp.rcp.supply.Activator;
import ru.jexp.utilities.StringUtil;

public class JExpLoginModel {

	private String login;

	public String getLogin() {
		return login;
	}

	public String[] getAvailableServers() {
		return availableServers.toArray(new String[0]);
	}

	private int server;

	private List<String> availableServers;

	private static final String LOGIN = "login";
	private static final String SERVER = "server";
	private static final String AVAILABLE_SERVER = "availableServer";

	public JExpLoginModel() {
		login = "";
		server = -1;
		availableServers = new ArrayList<String>();
		// default servers
		availableServers.add("212.33.239.47:8081");
		availableServers.add("192.168.77.30:8081");
		availableServers.add("192.168.59.1:8081");
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public void setServer(String server) {
		if (!availableServers.contains(server)) {
			availableServers.add(server);
		}
		this.server = availableServers.indexOf(server);
	}

	public int getServer() {
		return server;
	}

	public void restore() {
		IEclipsePreferences preferences = new ConfigurationScope()
				.getNode(Activator.PLUGIN_ID);
		login = preferences.get(LOGIN, "");
		server = preferences.getInt(SERVER, -1);
		availableServers = getAvailableServersToReStore(preferences.get(
				AVAILABLE_SERVER, ""));
	}

	public void store() {
		IEclipsePreferences preferences = new ConfigurationScope()
				.getNode(Activator.PLUGIN_ID);
		preferences.put(LOGIN, getLogin());
		preferences.putInt(SERVER, getServer());
		preferences.put(AVAILABLE_SERVER, getAvailableServersToStore());

		try {
			preferences.flush();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
	}

	private String getAvailableServersToStore() {
		StringBuffer buf = new StringBuffer();
		for (String server : availableServers) {
			buf.append(server);
			buf.append(";");
		}
		return buf.toString();
	}

	private List<String> getAvailableServersToReStore(String servers) {
		String[] split = servers.split(";");
		for (int i = 0; i < split.length; i++) {
			if (!StringUtil.isEmptyWithoutSpace(split[i])) {
				setServer(split[i]);
			}
		}
		return availableServers;
	}

}
